package cn.com.se.sharepictrue.utils;

import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Locale;

/**
 * 文件操作工具包
 *
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class FileUtils {

    public static boolean createFile(String filepath, boolean recursion) throws IOException {
        return createFile(new File(filepath), recursion);
    }

    public static boolean createFile(File file, boolean recursion) throws IOException {
        boolean result = false;
        if (!file.exists()) {
            try {
                result = file.createNewFile();
            } catch (IOException e) {
                if (!recursion) {
                    throw e;
                }
                File parent = file.getParentFile();
                if (!parent.exists())
                    parent.mkdirs();
                try {
                    result = file.createNewFile();
                } catch (IOException e1) {
                    throw e1;
                }
            }
        }
        return result;
    }

    /**
     * 获取固定格式大小字符串
     */
    public static String formatFileSize(long fileSize) {
        DecimalFormat df = new DecimalFormat("0.0");
        String fileSizeString = "0KB";
        if (fileSize < 1024L)
            fileSizeString = df.format(fileSize) + "B";
        else if (fileSize < 1048576L)
            fileSizeString = df.format(fileSize / 1024.0D) + "K";
        else if (fileSize < 1073741824L)
            fileSizeString = df.format(fileSize / 1048576.0D) + "M";
        else {
            fileSizeString = df.format(fileSize / 1073741824.0D) + "G";
        }
        return fileSizeString;
    }


    /**
     * 获取文件夹大小
     * Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
     * Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
     *
     * @param dir
     * @return
     */
    public static long getFolderSize(File dir) {
        if (dir == null) {
            return 0;
        }
        if (!dir.isDirectory()) {
            return 0;
        }
        long dirSize = 0;
        for (File file : dir.listFiles()) {
            if (file.isFile()) {
                dirSize += file.length();
            } else if (file.isDirectory()) {
                dirSize += getFolderSize(file); // 递归调用继续统计
            }
        }
        return dirSize;
    }

    /**
     * 获取文件后缀
     */
    public static String getFileExtension(File f) {
        if (f != null) {
            String filename = f.getName();
            int i = filename.lastIndexOf('.');
            if (i > 0 && i < filename.length() - 1) {
                return filename.substring(i + 1).toLowerCase(Locale.getDefault());
            }
        }
        return null;
    }

    /**
     * 获取文件名
     */
    public static String getUrlFileName(String url) {
        int slashIndex = url.lastIndexOf('/');
        int dotIndex = url.lastIndexOf('.');
        String filenameWithoutExtension;
        if (dotIndex == -1) {
            filenameWithoutExtension = url.substring(slashIndex + 1);
        } else {
            filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
        }
        return filenameWithoutExtension;
    }

    /**
     * 扩展名
     */
    public static String getUrlExtension(String url) {
        if (!TextUtils.isEmpty(url)) {
            int i = url.lastIndexOf('.');
            if (i > 0 && i < url.length() - 1) {
                return url.substring(i + 1).toLowerCase(Locale.getDefault());
            }
        }
        return "";
    }

    /**
     * 获取文件名
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }


    public static final StatFs mStatFs = new StatFs(Environment.getDataDirectory().getPath());

    /**
     * @return 手机内存总容量
     */
    public static long getTotalInternalMemorySize() {
        File path = Environment.getDataDirectory();
        mStatFs.restat(path.getPath());
        long blockSize = mStatFs.getBlockSize();
        long totalBlocks = mStatFs.getBlockCount();
        return totalBlocks * blockSize;
    }

    /**
     * @return 手机内存可用容量
     */
    public static long getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        mStatFs.restat(path.getPath());
        long blockSize = mStatFs.getBlockSize();
        long availableBlocks = mStatFs.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    /**
     * 否有外部存储设备
     *
     * @return
     */
    public static boolean isExternalStorageMounted() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * @return SD卡总容量
     */
    public static long getTotalExternalMemorySize() {
        if (isExternalStorageMounted()) {
            File path = Environment.getExternalStorageDirectory();
            mStatFs.restat(path.getPath());
            long blockSize = mStatFs.getBlockSize();
            long totalBlocks = mStatFs.getBlockCount();
            return totalBlocks * blockSize;
        } else {
            return -1;
        }
    }

    /**
     * @return SD卡可用容量
     */
    public static long getAvailableExternalMemorySize() {
        if (isExternalStorageMounted()) {
            File path = Environment.getExternalStorageDirectory();
            mStatFs.restat(path.getPath());
            long blockSize = mStatFs.getBlockSize();
            long availableBlocks = mStatFs.getAvailableBlocks();
            return availableBlocks * blockSize;
        } else {
            return -1;
        }
    }

    public static String getParentPath(final String path) {
        if (path == null)
            return null;
        String parenPath = null;
        int idx = path.lastIndexOf("/");
        if (idx != -1 && idx != 0)
            parenPath = path.substring(0, idx);
        return parenPath;
    }

    public static boolean isExists(String fileName) {
        File file = new File(fileName);
        return file.exists();
    }

    public static boolean writeStringToFile(String fileName, String content) {
        File file = new File(fileName);
        if (content == null)
            return false;

        if (!file.exists()) {
            String filepath = file.getAbsolutePath();
            String path = getParentPath(filepath);
            File dir = new File(path);
            dir.mkdirs();
        }
        FileOutputStream fos = null;
        byte[] data;
        try {
            fos = new FileOutputStream(file, false);
            data = content.getBytes();
            fos.write(data, 0, data.length);
            fos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fos) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            data = null;
            fos = null;
        }
        return false;
    }

    /**
     * 从文件中读取字符串内容
     */
    public static String readStringFromFile(String fileName, boolean addEnterLindEnd) {
        StringBuilder result = new StringBuilder();
        FileInputStream fip = null;
        InputStreamReader inputReader = null;
        BufferedReader bufReader = null;
        try {
            File file = new File(fileName);
            if (file.exists() && file.isFile()) {
                fip = new FileInputStream(file);
                inputReader = new InputStreamReader(fip);
                bufReader = new BufferedReader(inputReader);
                String line = "";
                while ((line = bufReader.readLine()) != null) {
                    if (addEnterLindEnd) {
                        result.append(line + "\n");
                    } else {
                        result.append(line);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bufReader) {
                    bufReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != inputReader) {
                    inputReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != fip) {
                    fip.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result.toString();
    }
}